/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <ohos_init.h>
#include <los_task.h>
#include <string.h>
#include "esp_http_server.h"
#include "romfs.h"
#include "response_request.h"

#define CHECK_FILE_EXTENSION(filename, ext) (strcasecmp(&filename[strlen(filename) - strlen(ext)], ext) == 0)

httpd_handle_t g_httpServer = NULL;
extern const struct romfs_dirent romfs_web_page;
int get_index_handler(httpd_req_t *req);

static const httpd_uri_t uri_tab[]= {
    {"/assets/Adapter-B469q59z.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/Adapter-s2QKmby4.css", HTTP_GET, get_index_handler, NULL},
    {"/assets/FormItem-C9OBM9nc.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/common-BRxve60L.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/edit-B3Y-fHTC.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/equipment-network-CcV9ZXbC.css", HTTP_GET, get_index_handler, NULL},
    {"/assets/equipment-network-iE5xIjCT.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/image-BW1SMX3k.png", HTTP_GET, get_index_handler, NULL},
    {"/assets/image_copy_5-C-mqJOOQ.png", HTTP_GET, get_index_handler, NULL},
    {"/assets/index-CIncC6g7.css", HTTP_GET, get_index_handler, NULL},
    {"/assets/index-D9Kw_Bnj.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/inputProps-B8rfyox6.css", HTTP_GET, get_index_handler, NULL},
    {"/assets/inputProps-CmMJI1tU.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/login-BpVKUhZF.css", HTTP_GET, get_index_handler, NULL},
    {"/assets/login-C3rDiVA2.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/login_bg-BtUTjNWJ.png", HTTP_GET, get_index_handler, NULL},
    {"/assets/network-ZPdJGL4V.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/ota-service-CP3Uu92W.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/ota-service-J-OwXloK.css", HTTP_GET, get_index_handler, NULL},
    {"/assets/server-BqJ6v168.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/time-service-CLOk2L4D.css", HTTP_GET, get_index_handler, NULL},
    {"/assets/time-service-DQDaEQed.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/voucher-issuance-DZXKvbG3.css", HTTP_GET, get_index_handler, NULL},
    {"/assets/voucher-issuance-RNVUbfPX.js", HTTP_GET, get_index_handler, NULL},
    {"/assets/favicon.svg", HTTP_GET, get_index_handler, NULL},
    {"/", HTTP_GET, get_index_handler,  NULL},
    {"/login_set", HTTP_POST, response_post_set_login, NULL},
    {"/login", HTTP_POST, response_post_login, NULL},
    {"/main/uart_get", HTTP_GET, response_get_uart_config, NULL},
    {"/main/uart_set", HTTP_POST, response_post_uart_config, NULL},
    {"/net/info", HTTP_GET, response_get_net_info, NULL},
    {"/net/net_get", HTTP_GET, response_get_net_config, NULL},
    {"/net/net_set", HTTP_POST, response_post_net_config, NULL},
    {"/voucher_get", HTTP_GET, response_get_voucher_config, NULL},
    {"/voucher_set", HTTP_POST, response_post_voucher_config, NULL},
    {"/ntp_get", HTTP_GET, response_get_ntp_config, NULL},
    {"/ntp_set", HTTP_POST, response_post_ntp_config, NULL},
    {"/ota_get", HTTP_GET, response_get_ota_config, NULL},
    {"/ota_set", HTTP_POST, response_post_ota_config, NULL},
};

static inline int set_content_type_from_file(httpd_req_t *req, const char *filepath)
{
    const char *type = "text/plain";
    if (CHECK_FILE_EXTENSION(filepath, ".html")) {
        type = "text/html";
    } else if (CHECK_FILE_EXTENSION(filepath, ".js")) {
        type = "application/javascript";
    } else if (CHECK_FILE_EXTENSION(filepath, ".css")) {
        type = "text/css";
    } else if (CHECK_FILE_EXTENSION(filepath, ".png")) {
        type = "image/png";
    } else if (CHECK_FILE_EXTENSION(filepath, ".ico")) {
        type = "image/x-icon";
    } else if (CHECK_FILE_EXTENSION(filepath, ".svg")) {
        type = "text/xml";
    }
    printf("set resp type: %s\n", type);
    return httpd_resp_set_type(req, type);
}

int get_index_handler(httpd_req_t *req)
{
    httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");        /* 跨域传输协议 */
    char filepath[256]={0};
    
    if (req->uri[strlen(req->uri) - 1] == '/') {
        strlcat(filepath, "/index.html", sizeof(filepath));             /* 串接字符串 */
    } else {
        httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
        strlcat(filepath, req->uri, sizeof(filepath));                  /* 串接请求文件 */
    }
    printf("file path: %s\n", filepath);
    set_content_type_from_file(req, filepath);                          /* 设置传输类型 */

    size_t data_len = 0;
    struct romfs_dirent *root_dirent = (struct romfs_dirent *)&romfs_web_page;
    struct romfs_dirent *data = dfs_romfs_lookup(root_dirent, filepath, &data_len);
    
    if(data == NULL){
        printf("file NULL\n");
        httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Failed to send file");
        return 0;
    }

    return httpd_resp_send(req, (const char*)data->data, data->size);
}

/* 开启 http server */
void start_http_server()
{
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    config.stack_size = 8192;
    config.max_uri_handlers = 64;       /* url 数量 */
    config.max_resp_headers = 32;       /* 响应 数量 */

    printf("Starting http server on port: %d Version:%s\n", config.server_port, JH_WEB_VERSION);
    if(httpd_start(&g_httpServer, &config) == 0) {
        uint8_t num = sizeof(uri_tab)/sizeof(uri_tab[0]);
        for (uint8_t i = 0; i < num; i++)
        {
            httpd_register_uri_handler(g_httpServer, &uri_tab[i]);
        }
    }
}

/* 停止 http server */
void stop_http_server()
{
    if(NULL == g_httpServer){
        return;
    }
    httpd_stop(g_httpServer);
}

// APP_FEATURE_INIT(start_http_server);
